from rest_framework import serializers

from model_app.models import BookInfo, HeroInfo


class BookInfoSerializer(serializers.Serializer):
    # 自定 字段和字段属性,  和model一致,
    # 字典, btitle
    btitle = serializers.CharField(max_length=64, min_length=1)
    bpub_date = serializers.DateField()
    bread = serializers.IntegerField()
    bcomment = serializers.IntegerField()

    def validate_btitle(self, attrs):
        return attrs * 2

    def create(self, validated_data):
        book = BookInfo.objects.create(**validated_data)
        return book


class HeroInfoSerializer(serializers.Serializer):
    # 自定 字段和字段属性,  和model一致,
    # 字典, btitle
    hname = serializers.CharField(max_length=20)
    hgender = serializers.IntegerField()
    hcomment = serializers.CharField(max_length=200)
    hbook = serializers.CharField()  # 外键  取外键id,

    def create(self, validated_data):
        hbook_id = validated_data.pop('hbook')
        validated_data['hbook_id'] = hbook_id
        book = HeroInfo.objects.create(**validated_data)
        return book


class BookInfoModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = '__all__'
        # fields = ['btitle', ]


class HeroInfoModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = HeroInfo
        fields = '__all__'
        # fields = ['btitle', ]
